#include "sendfile.h"
#include <QThread>
#include <QDebug>
#include <QFileInfo>
#include <QFile>
#include <QHostAddress>

SendFile::SendFile(QObject *parent) : QObject(parent)
{
}

SendFile::~SendFile()
{
    qDebug() << "dead......"; 
    #if 0
    qDebug() << "hhhhh1"; 
    if(this->sfd) 
    {
        qDebug() << "hhhhh2"; 
        this->sfd->close(); 
    }
    delete this->sfd; 
    #endif 
}

void SendFile::connectServer(QString ip, unsigned short port)
{
    qDebug() << "connectServe"; 
    this->sfd = new QTcpSocket; 
    this->sfd->connectToHost(QHostAddress(ip), port); 
    connect(this->sfd, &QTcpSocket::connected, this, &SendFile::connect_OK);
    connect(this->sfd, &QTcpSocket::disconnected, this, [=]()
    {
        if(this->sfd) this->close();
        emit disconnect_OK();
    }); 
}

void SendFile::sendFile(QString path)
{
    qDebug() << "sendFile"; 
    
    QFile file(path); 
    if(!file.open(QFile::ReadOnly)) 
    {
        emit openfile_error(); 
        return; 
    }

    QFileInfo info(path); 
    QByteArray filename = info.fileName().toUtf8(); 
    int fileSize = info.size(), sendsum = 0;
    
    this->sfd->write((char*)&fileSize, sizeof(int)); 
    //this->sfd->write((char*)&filename_length, sizeof(int)) ; 
    this->sfd->write(filename + '\n'); 
    
    while(!file.atEnd())
    {
        QByteArray line = file.readLine(); 
        sendsum += line.size(); 
        emit send_percent(sendsum * 100 / fileSize); 
        this->sfd->write(line); 
    }
    qDebug() << "sendFile    end"; 
}

void SendFile::close() 
{
    this->sfd->close(); 
    this->sfd->deleteLater(); 
    this->sfd = nullptr; 
}